'''
Created on 2011-1-24

@author: siqi
'''
import os,time, DescriptionParser,thread,sys
from Configuration import Configuration
cf = Configuration()
openTTDPath = "J:\\VSworkspace\\orign1.05\\bin\\openttd" 
targetFilePath = "J:\\sav\\score"

def startOpenttd(filename):
    cmd = openTTDPath + " -g " + filename + " -V -v null"
    print cmd
    print "generating ",  filename
    os.system(cmd)

def getCompanyScore(filename, dumpFilePath = "c:\\companyScore.txt"):
    cmd = openTTDPath + " -g " + filename + " -V"
    newfilepath = filename + "_companyScore.txt"
#    newfilepath = targetFilePath + "\\\\" + newfilepath
   
#    print "invoking openttd"
#    print cmd
#    os.system(cmd)
    thread.start_new_thread(startOpenttd, (filename,))
#    print "invoked"
    while os.path.exists(dumpFilePath) == False:
        time.sleep(1)
    print "mv " + dumpFilePath + " " + newfilepath
    os.system("mv " + dumpFilePath + " " + newfilepath)
#    print "killing"
    if(sys.platform.find("win")>=0):
        os.system("pskill openttd")
    else:
        os.system("killall -9 saveload")
        os.system("killall -9 openttd")
#    print "killed"

    
def getAllCompanyScore(expName, expId = 0):
    path = cf.getAutoSavePath(expName)
    for factor in DescriptionParser.getFactors(expName):
        if expId == 0:
            nameTemplate = expName + "_%d_"%factor
        else:
            nameTemplate = "%d_"%expName + "_%d_"%factor
#        print os.listdir(path)
        for file in os.listdir(path):
            if file.find(nameTemplate)>=0 and file.endswith(".sav"):
                getCompanyScore(path + "\\\\" + file)
                
if __name__ == "__main__":
    for expName in ["1a3"]:
        getAllCompanyScore(expName)